package leetcode;

public class LC1419 {

    public static int minNumberOfFrogs(String croakOfFrogs) {
        while (croakOfFrogs.startsWith("croak")) {
            croakOfFrogs = croakOfFrogs.replaceFirst("croak","");
            if (croakOfFrogs.equals("")) return 1;
        }
        while (croakOfFrogs.endsWith("croak")) {
            croakOfFrogs = croakOfFrogs.substring(0,croakOfFrogs.length()-5);
            if (croakOfFrogs.equals("")) return 1;
        }
        int[] cnt = new int[5];
        for (int i = 0; i < croakOfFrogs.length(); i++) {
            if (croakOfFrogs.charAt(i) == 'c') {
                if (cnt[4] > 0) { // 前面有青蛙叫完一声了，接着叫，青蛙数不增加
                    cnt[0]--;
                    cnt[1]--;
                    cnt[2]--;
                    cnt[3]--;
                    cnt[4]--;
                }
                cnt[0] ++;
            }
            else if (croakOfFrogs.charAt(i) == 'r') {
                if (cnt[0] > cnt[1])  cnt[1] ++;
                else return -1;
            }
            else if (croakOfFrogs.charAt(i) == 'o' ) {
                if (cnt[1] > cnt[2]) cnt[2] ++;
                else return -1;
            }
            else if (croakOfFrogs.charAt(i) == 'a' ) {
                if (cnt[2] > cnt[3]) cnt[3] ++;
                else return -1;
            }
            else if (croakOfFrogs.charAt(i) == 'k' ) {
                if (cnt[3] > cnt[4]) cnt[4] ++;
                else return -1;
            }
            else return -1;
        }
        if (cnt[0] == cnt[1] && cnt[0] == cnt[2] && cnt[0] == cnt[3] && cnt[0] == cnt[4])
            return cnt[0];
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(minNumberOfFrogs("crocakcroraoakk"));
    }
}
